﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Workflows.Components.Reports
{
    public delegate void ColumnBindingsChanged(ExcelDataRegion dataRegion, Dictionary<string, string> bindings);

    public partial class ExcelColumnBinding : Form
    {
        public event ColumnBindingsChanged OnColumnBindingsChanged;
        private ExcelDataRegion _DataRegion;

        public ExcelColumnBinding()
        {
            InitializeComponent();
        }

        public void SetColumns(ExcelDataRegion dataRegion, List<string> srcColNames, List<string> excelColumns)
        {
            this._DataRegion = dataRegion;
            this.dv_Bindings.Rows.Clear();
            foreach (string srcColName in srcColNames)
            {
                DataGridViewRow dr = new DataGridViewRow();
                DataGridViewComboBoxCell cellSrc = new DataGridViewComboBoxCell();
                cellSrc.Items.Add("");
                for (int i = 0; i < srcColNames.Count; i++)
                {
                    cellSrc.Items.Add(srcColNames[i]);
                }
                dr.Cells.Add(cellSrc);
                DataGridViewComboBoxCell cellTgt = new DataGridViewComboBoxCell();
                cellTgt.Items.Add("");
                for (int i = 0; i < excelColumns.Count; i++)
                {
                    cellTgt.Items.Add(excelColumns[i]);
                }
                dr.Cells.Add(cellTgt);
                this.dv_Bindings.Rows.Add(dr);
            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> bindings = new Dictionary<string, string>();
            foreach (DataGridViewRow dr in this.dv_Bindings.Rows)
            {
                if (!dr.IsNewRow && dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                {
                    string srcName = dr.Cells[0].Value.ToString();
                    string tgtName = dr.Cells[1].Value.ToString();
                    if ((!string.IsNullOrEmpty(srcName)) && (!string.IsNullOrEmpty(tgtName)))
                    {
                        bindings.Add(srcName, tgtName);
                    }
                }
            }
            if (this.OnColumnBindingsChanged != null)
            {
                this.OnColumnBindingsChanged(this._DataRegion, bindings);
            }
            this.Close();
        }
    }
}
